<?php







namespace Home\Controller;







/**



* 课程类



*/



class CourseController extends HomeController



{



	/**



	 * 发布课程



	 * @param  [int] $teaching [1教or2学]



	 * @param  [int] $id       [课程id]



	 * @author qlj



	 */



	public function addcourse($teaching, $id=''){



		if (IS_POST) {



			//如果发布教学
			// if(!D('Auth') ->where(array('uid' =>session('uid'))) ->find()){
			// 	$this ->error('没有认证身份不能发布课程');die;
			// }
			if(empty($_POST['label'])){



				$this ->error('没有选择分类。');



			}



			if ($_POST['title'] == '') {



				$this -> error('请填写课程名称');



			}



			if (mb_strlen($_POST['title'],'UTF8') > 5) {



				$this -> error('课程标题字数超过限制（5个字）');



			}



			if ($_POST['content'] == '') {



				$this -> error('请填写自我介绍');



			}



			if (mb_strlen($_POST['content'],'UTF8') > 140) {



				$this -> error('自我介绍超过字数限制（140字）');



			}



			if ($_POST['salary'] == '' || !is_numeric($_POST['salary'])) {



				$this -> error('请用纯数字填写价格');



			} elseif (intval($_POST['salary']) < 10) {



				$this -> error('时薪最低10元哦');



			} elseif (intval($_POST['salary']) > 300) {



				$this -> error('时薪最高300元哦');



			}



			$_POST['uid'] = session('uid');



			$_POST['create_time'] = time();



			// dump($_POST);die;



			if (!empty($_POST['id'])) {

				
				/* lkl处理，如果只修改价格，则不需要重新审核 */
				$flg = 0;
				$bmsg = '';
				if($_POST['label'] == $_POST['oldlabel'] && 
					$_POST['title'] == $_POST['oldtitle'] &&
					$_POST['content'] == $_POST['oldcontent']){
						if($_POST['salary'] == $_POST['oldsalary']){
							
							$this -> success('您的内容已没有做过改动。',U('Course/mycourses',array('teaching' => $teaching)));
						}else{
							
							$flg = 1;
						}
						
					}else{
						$_POST['passed'] = 0;
					}
					
					unset($_POST['oldlabel']);
					unset($_POST['oldtitle']);
					unset($_POST['oldsalary']);
					unset($_POST['oldcontent']);

				if (D('Course') -> save($_POST)) {

					if($flg == 0){
						$bmsg = "您的内容已提交，我们会尽快审核";
					}else{
						$bmsg = "您的内容修改成功";
					}
					$this -> success($bmsg,U('Course/mycourses',array('teaching' => $teaching)));



				} else {



					$this -> error('出错了');



				}



			} else {



				$courses = D('Course') -> userCourses(session('uid'),$teaching);



				if (count($courses) < 5) {



					if (D('Course') -> addcourse($_POST)) {



						$this -> success('您的内容已提交，我们会尽快审核。',U('Course/mycourses',array('teaching' => $teaching)));



					} else {



						$this -> error('出错了');



					}



				} else {



					$this -> error('最多只能发布5门课程哦');



				}



				



			}



		} else {



			if (empty($_GET['teaching'])) {



				$_GET['teaching'] = 1;



			}



			//如果发布教学



			// if ($_GET['teaching'] == 2) {



			// 	$uid 	= session('uid');



			// 	$result = D('Auth') -> find($uid);



			// 	if (empty($result)) {



			// 		$this -> error('当老师请先认证身份', U('Auth/add'));



			// 	} elseif ($result['passed'] != 1) {



			// 		$this -> error('您的身份认证尚未通过，请通过后再试', U('Index/index'));



			// 	}



			// }



			//如果传课程id



			if ($id != '') {



				//查找课程详情，载入页面



				//$course = D('Course') -> userCourses(session('uid'), $teaching, $id, 1);
				$course = D('Course') -> userCourses(session('uid'), $teaching, $id);//lkl修改，读取所有状态的信息



				//去掉整数后的.00



				$course['salary'] = ($course['salary'] == (int)$course['salary']) ? (int)$course['salary'] : $course['salary'];



				$this -> assign('course', $course);



			}



			$label = getIteam('label');



			$this -> assign('label', $label);
			
			$this -> assign('teaching', $teaching);//lkl新增类型



			$this -> display();



		}



	}







	/**



	 * 预约课程页面



	 * @param  [int] $uid      [老师id]



	 * @param  [int] $teaching [教or学]



	 * @author qlj



	 */



	public function userCourses($uid='', $teaching=''){



		//存取cookie，用于支付失败后跳转



		if (!empty($uid) && !empty($teaching)) {



			setcookie('uid',$uid,time()+600);



			setcookie('teaching',$teaching,time()+600);



		} else {



			$uid = $_GET['uid'] = $_COOKIE['uid'];



			setcookie('uid','',time()-3600);



			$teaching = $_GET['teaching'] = $_COOKIE['teaching'];



			setcookie('teaching','',time()-3600);



		}



		



		if($_SESSION['wx_openid']){



			$this->wx_openid();



		}



		$courses = D('Course') -> userCourses($uid,$teaching);







		//查找用户,用以获取手机号



		$user = D('UserMember') -> showUser(session('uid'));







		$this -> assign('courses', $courses);



		$this -> assign('user',$user);



		$this -> assign('tid',$uid);



		$this -> display();



	}







	/**



	 * [预约成功]



	 * @author qlj



	 */



	public function successful(){



				//支付流程3



				if(IS_POST){



					//添加订单表



				$order['order']=NOW_TIME;



				$order['uid']=session('uid');



				$order['cid']=$_POST['id'];



				$order['tid']=$_POST['tid'];



				$order['num']=$_POST['num'];



				$order['salary']=$_POST['salary'];



				$order['price']=$_POST['price'];



				$return=D('order')->update($order);



				$return =D('order')->where(array('id'=>$return))->find();



				$out=$return['order'];



				$Columns=A("Wxpay");



   				$ree=$Columns->weixinpay_js($out);//支付完成



				}







	}







	/**



	 * [编辑发布自我介绍]



	 * @param  [int] $teaching [教or学]



	 * @author qlj



	 */



	public function released($teaching){
		if (empty($teaching)) {
			$teaching = 1;
		}
		if (IS_POST) {
			if($_FILES){
                                $logo = $_FILES;
                                $arr['rootPath']="./Uploads/Picture/";
                                $logo['logo']['is_thumb']=true;
                                $file=D('Picture')->upload($logo,$arr);
                                $_POST['qr_code']=$file['logo']['id'];
			}
			// dump($rees);die;
			//如果检测到id，为修改数据
			// dump($_POST);die;
			// if(empty($_FILES)){

			// }
			
			
			$url = $_SERVER['HTTP_REFERER'];//lkl修改

			if (!empty($_POST['id'])) {
                                
                                if($_POST['area_id'] == ""){
                                     header('Location:'.$url."&msg='未填选位置信息。'");die; 
                                }
                                D('UserMember') ->updateArea($_POST['area_id']);
				if (mb_strlen($_POST['inaword'],'UTF8') > 22) {
                                        //$this -> assign('msg','一句话超过字数限制（22个字）');
                                        header('Location:'.$url."&msg='一句话超过字数限制（22个字）'");die; 

				}
				if (mb_strlen($_POST['introduce'],'UTF8') > 140) {
                                        header('Location:'.$url."&msg='自我介绍超过字数限制（140个字）'");die; 
				}
				$_POST['update_time'] = time();    
				if (D('introduce') -> save($_POST)) {
                                    $data['update_time'] = $_POST['update_time']; 
                                    if(!empty($_POST['qr_code'])){
                                       $data['qr_code']     = $_POST['qr_code'];
                                    }
                                        if(D('UserMember') ->where(array('id' => session('uid'))) ->save($data)){
									header('Location:'.$url."&msg='修改成功'");die; 

                                        }
				} else {
					header('Location:'.$url."&msg='修改成功'");die; 
				}
			} else {
				//添加数据
				$_POST['uid']  = session('uid');
				$_POST['type'] = $teaching;
				if (D('introduce') -> add($_POST)) {
                                        if(D('UserMember') ->where(array('id' =>session('uid'))) ->save(array('qr_code' =>$_POST['qr_code']))){
					header('Location:'.$url."&msg='修改成功'");die; 
                                        }
				} else {
                                        header('Location:'.$url."&msg='修改失败'");die; 

					//$this -> error('出错了');

				}

			}
		} else {



			//查看是否认证



			// if ($teaching == 2) {



			// 	$result = D('Auth') -> showFind(session('uid'));



			// 	if (empty($result)) {



			// 		$this -> error('请先认证身份',U('Auth/add'));



			// 	} elseif ($result['passed'] != 1) {



			// 		$this -> error('您的身份认证尚未通过',U('Index/index'));



			// 	}



			// }



			$courses = D('Course') -> userCourses(session('uid'),$teaching,'',$flag=1);
			// dump($courses);die;



			//去掉整数后的.00



			foreach ($courses as &$v) {



				$v['salary'] = ($v['salary'] == (int)$v['salary']) ? (int)$v['salary'] : $v['salary'];



			}



			unset($v);



			$introduce = D('introduce') -> detail(session('uid'),$teaching);



			$info = D('UserMember') -> showUser(session('uid'));



			if ($teaching == 2) {
				//是否停止授课
				$end_teach = $info['end_teach'];
				$this -> assign('end_teach', $end_teach);
                                //lkl修改教学简介的标题
                                $intro = '我想教';
                                $this->assign('intro',$intro);
			} elseif ($teaching == 1) {
				//是否停止学习
				$end_study = $info['end_study'];
				$this -> assign('end_study', $end_study);
                                //lkl修改教学简介的标题
                                $intro = '我想学';
                                $this -> assign('intro', $intro);
			}
                        $data = D('UserMember') ->field('area_id,area_id') -> where(array('id'=>session('uid'))) -> find();
                        $areas = D('Area') -> getAreas();
			$towArea =D('UserMember') ->towArea($data['area_id'],2);
                        $sheng = D('UserMember') ->sheng($data['area_id']);
                        $this ->assign('sheng',$sheng);
			$this ->assign('towArea',$towArea);

			$this ->assign('data',$data);

			$this ->assign('areas', $areas);

            $qr_code=getLogin(session('uid'),'qr_code');


			$this->assign('pics',$qr_code);

			// echo M() -> _sql();

			$this -> assign('courses', $courses);



			$this -> assign('introduce', $introduce);



			$this -> assign('pause', get_pause(session('uid')));



			$this -> display();



		}



	}







	/**



	 * 我发布的课程



	 * @param  [int] $teaching [教or学]



	 * @author qlj



	 */



	public function myCourses($teaching){



		$courses = D('Course') -> userCourses(session('uid'), $teaching);

		//去掉整数后的.00



		foreach ($courses as &$v) {



			$v['salary'] = ($v['salary'] == (int)$v['salary']) ? (int)$v['salary'] : $v['salary'];



		}



		unset($v);



		$this -> assign('courses', $courses);
		$this -> assign('teaching', $teaching);//lkl新增类型


		$this -> display();



	}







	/**



	 * [cancel description]学生取消课程



	 * @return [type] [description]



	 */



	public function cancel(){



		$uid  = I('get.uid');



		$cid  = I('get.cid');



		//获取个人信息



		$data = D('Course') -> findCancel($uid,$cid);



		$this ->assign('data',$data);



		//获取剩余的课程



		$time = D('CourseRecord') ->showTime($uid,$cid);



		$this ->assign('time',$time);



		//获取一个时间戳



		$date = time();



		$this ->assign('data',$data);



		//取出课时



		$this ->assign('num',$num);



		//剩余的课时



		$num = D('Course') -> findNum($uid,$cid);



		$this ->assign('num',$num);



		$this ->display();



	}



	/**



	 * [affirm description]查找确认后的页面



	 * @return [type] [description]



	 */



	public function affirm(){



		$uid  = I('get.uid');



		$cid  = I('get.cid');



		//先把个人信息查询出来



		$data = D('Course') ->selectCourse($uid,$cid);



		$this ->assign('data',$data);



		//查询所有时间



		$time = D('CourseRecord') ->showTime($uid,$cid);



		$this ->assign('time',$time);



		//取一个时间戳



		$date = time();



		$this ->assign('date',$date);



		//查询已经上了的课时



		$num  = D('Mycourse') ->showTimeNum($time,$date);



		$this ->assign('num',$num);



		$this ->display();



	}



	/**



	 * 评论以后展示评论的页面



	 */



	public function showAssess(){



		//教师的id



		$uid   = I('get.uid');



		$cid   = I('get.cid');



		$result = D('Course') ->field('uid') ->where(array('id' =>$cid)) ->find();



		$uid = $result['uid'];



		$order = I('get.order');



		//查找班级老师的信息



		$data = D('Course') ->showCourseMsg($uid,$cid);



		$this ->assign('data',$data);



		//查找自己评论的数据



		$uid = $_SESSION['onethink_home']['uid'];



		$eva  = D('Course') ->showEva($cid,$uid,$order);

		

		$this ->assign('eva',$eva);



		//查找所有的上课时间



		$time = D('CourseRecord') ->showTimeOrder($order);



		$this ->assign('time',$time);



		//查找老师的回复



		$reply = D('Reply') ->showReply($eva['id']);



		$this ->assign('reply',$reply);



		$this ->display();



	}



    public function wx_openid() {



    $appid = "wx24af86636d874b65";



    $redirect_uri = urlencode("http://test.qlzhx.cn/wapjiaoyu/index.php?s=/Home/Pay/codes");



    $wxurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";



    header("Location:$wxurl");



}



    // 获取openid



    public function codes(){



        $appid = "wx24af86636d874b65";



        $secret = "cf8e1c33e151589634b9f9d3a1c96c26";



        $wxinfo = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$_GET['code']."&grant_type=authorization_code";



        $info = json_decode(file_get_contents($wxinfo),true);



        session('wx_openid',$info['openid']);



        $url = "http://test.qlzhx.cn/wapjiaoyu/index.php?s=/Home/Course/userCourses";



        header("Location:$url");



    }



    public function delCourse(){



    	$id = I('post.id');



    	$result = D('CourseRecord') -> is_complete('',$id);



    	if (!empty($result)){



    		$this -> ajaxReturn('当前课程还有学生哦~');



    	} else {



	    	//$data = D('Course') ->where(array('id' =>$id)) ->save(array('status' =>2));
			/* lkl修改，删除不是只改状态，是彻底删除 */
			$data = D('Course') ->where(array('id' =>$id)) ->delete();

	    	if($data){



	    		$this ->ajaxReturn('删除成功！');



	    	}else{



	    		$this ->ajaxReturn('删除失败！');



	    	}



    	}



    }



    /**



     *撤销的方法



     */



    public function ontOrder(){



		$order = I('get.order');



		//给老师发消息



		D('Order') -> teacheMsg($order);



		if(D('Order') ->notCancel($order)){



			$this ->success('取消退订成功',U('index'));



		}else{



			$this ->success('取消退订失败',U('index'));



		}



	}    



}